package com.egoonet.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.egoonet.util.CommonUtil;
import com.google.common.base.Strings;

@WebServlet(value="/startservlet", loadOnStartup=1)
public class StartServlet  extends HttpServlet{
	private static final long serialVersionUID = 6972976602979414687L;
	private static final Logger logger = LoggerFactory.getLogger(StartServlet.class);
	
	public void init() throws ServletException {
		logger.info("开始启动服务");
		try {
			logger.debug("开始更新版本信息");
			updateGitCommitId();
		} catch (IOException e) {
		}
	}
	
	public void destroy() {
		logger.info("开始关闭服务 ...");
	}
	
	/**
	 * 更新配置文件中的git提交版本号
	 * @throws IOException 
	 */
	private void updateGitCommitId() throws IOException {
		String srcPath = System.getenv("srcfolder");
		if (Strings.isNullOrEmpty(srcPath)) {
			logger.debug("不是开发环境，跳过设置commit_id");
			return;
		}

		// log.debug("源代码目录为[{}]", srcPath);
		String srcPath_git = srcPath + File.separator + ".git";
		File file = new File(srcPath_git);
		if (!file.exists() || !file.isDirectory()) {
			logger.debug("git目录不存在，跳过设置commit_id");
			return;
		}

		// 获取git最新一次提交信息
		String[] rtArray = CommonUtil.getGitCommitIdAndLog(srcPath);
		if (rtArray == null) {
			logger.info("不需要设置commit_id与log，因获取git信息失败");
			return;
		}

		logger.debug("开始设置配置文件的commit信息, commitId[{}], commitLog[{}]", rtArray[0], rtArray[1]);
		// 将git提交日志写入到文件中，便于版本跟踪
		FileOutputStream outputStream = null;
		OutputStreamWriter streamWriter = null;
		try {
			outputStream = new FileOutputStream(srcPath + "/src/commit.log");
			streamWriter = new OutputStreamWriter(outputStream, "UTF-8");
			streamWriter.write("commit_id=" + rtArray[0]);
			streamWriter.write("\ncommit_log=" + rtArray[1]);
			streamWriter.write("\ncommit_time=" + rtArray[2]);
			streamWriter.write("\ncommit_user=" + rtArray[3]);
			streamWriter.flush();
			
		} catch (Exception e) {
			logger.warn("在写入配置commit.log时出现异常", e);
		} finally {
			if (streamWriter != null)
				streamWriter.close();
			if (outputStream != null)
				outputStream.close();
		}
	}
}
